package com.hexus.eve.entities.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.hexus.eve.entities.Account;

@Entity
@Table(name="users")
public class User implements UserDetails{
	private static final long serialVersionUID = 1L;

	@Transient
	private List<GrantedAuthority> authorities;
	
	@Id
	@Column(name="username")
	private String name = "";
	private String password = "";
	private Boolean enabled = false;
	private String email = "";


	@ManyToMany
	@LazyCollection(LazyCollectionOption.FALSE)
	@JoinTable(name="group_members", joinColumns={@JoinColumn(name="username")}, inverseJoinColumns={@JoinColumn(name="group_id")})
	private List<SecurityGroup> groups = new ArrayList<SecurityGroup>();
	
	@OneToMany
	@LazyCollection(LazyCollectionOption.FALSE)
	@JoinTable(name="user_accounts", joinColumns={@JoinColumn(name="username")}, inverseJoinColumns={@JoinColumn(name="id")})
	private List<Account> accounts = new ArrayList<Account>();	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public List<Account> getAccounts() {
		return accounts;
	}
	
	public List<SecurityGroup> getGroups() {
		return groups;
	}
	
	public void setGroups(List<SecurityGroup> groups) {
		this.groups = groups;
	}

	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	
	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(List<GrantedAuthority> authorities) {
		this.authorities = authorities;
	}
	
	@Override
	public String getUsername() {
		return name;
	}

	@Override
	public boolean isAccountNonExpired() {
		return enabled;
	}

	@Override
	public boolean isAccountNonLocked() {
		return enabled;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return enabled;
	}

	@Override
	public boolean isEnabled() {
		return enabled;
	}

}
